﻿using Autofac;
using System;
using System.Linq;
using System.Reflection;
using Loong.Extensions;

namespace Loong.Dependency
{
    public static class ContainerBuilderExtensions
    {
        public static void RegisterAssemblyByConvention(this ContainerBuilder builder, Assembly assembly)
        {
            builder.RegisterAssemblyTypes(assembly)
                .Where(type => typeof(ITransientDependency).IsAssignableFrom(type))
                .As(type => type.GetInterfaces().Where(i => type.Name.Contains(GetInterfaceName(i))))
                .AsSelf()
                .InstancePerDependency();

            builder.RegisterAssemblyTypes(assembly)
                .Where(type => typeof(IScopedDependency).IsAssignableFrom(type))
                .As(type => type.GetInterfaces().Where(i => type.Name.Contains(GetInterfaceName(i))))
                .AsSelf()
                .InstancePerLifetimeScope();

            builder.RegisterAssemblyTypes(assembly)
                .Where(type => typeof(ISingletonDependency).IsAssignableFrom(type))
                .As(type => type.GetInterfaces().Where(i => type.Name.Contains(GetInterfaceName(i))))
                .AsSelf()
                .SingleInstance();
        }

        private static string GetInterfaceName(Type @interface)
        {
            var name = @interface.Name;
            if ((name.Length > 1 && name[0] == 'I') && char.IsUpper(name[1]))
            {
                return name.Substring(1);
            }
            return name;
        }
    }
}
